package cn.edu.sgu.www.mhxysy.listener;

import cn.edu.sgu.www.mhxysy.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * 自定义的容器事件监听类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Slf4j
@Component
public class CustomEventListener {

    /**
     * 应用名
     */
    @Value("${spring.application.name}")
    private String name;

    /**
     * 文件上传临时目录
     */
    @Value("${uploads.temp-dir}")
    private String tempDir;

    /**
     * 监听容器启动事件
     */
    @EventListener(ApplicationStartedEvent.class)
    public void listenStartEvent() {
        log.debug("监听到容器启动事件，执行CustomEventListener.listenStartEvent()方法...");

        // 项目启动时创建临时目录
        String temp = tempDir + "/" + name;

        FileUtils.createFolder(temp);
    }

    /**
     * 监听容器关闭事件
     */
    @EventListener(ContextClosedEvent.class)
    public void listenCloseEvent() {
        log.debug("监听到容器关闭事件，执行CustomEventListener.listenCloseEvent()方法...");

        // 项目停止时删除临时目录
        String temp = tempDir + "/" + name;

        boolean delete = FileUtils.delete(temp);

        if (delete) {
            log.debug("应用关闭，清理临时目录...");
        }
    }

}